import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SwapOutlined, ToolOutlined, CloseOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, Select, DatePicker, message, Tabs, Tag } from 'antd';

import { assetApi } from '../../api/assetApi';
import dayjs from 'dayjs';

const { Option } = Select;
const { TabPane } = Tabs;

export default function AssetManagement() {
  const [loading, setLoading] = useState(false);
  const [fixedAssets, setFixedAssets] = useState([]);
  const [currentAssets, setCurrentAssets] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [assetType, setAssetType] = useState('fixed');
  const [form] = Form.useForm();

  useEffect(() => {
    fetchAssets();
  }, []);

  const fetchAssets = async () => {
    setLoading(true);
    try {
      const [fixedResponse, currentResponse] = await Promise.all([
        assetApi.getFixedAssets(),
        assetApi.getCurrentAssets()
      ]);
      setFixedAssets(fixedResponse.data);
      setCurrentAssets(currentResponse.data);
    } catch (error) {
      message.error('获取资产列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = (type) => {
    setAssetType(type);
    setEditingRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record, type) => {
    setAssetType(type);
    setEditingRecord(record);
    form.setFieldsValue({
      ...record,
      purchaseDate: record.purchaseDate ? dayjs(record.purchaseDate) : null,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id, type) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条资产记录吗？',
      onOk: async () => {
        try {
          if (type === 'fixed') {
            await assetApi.deleteFixedAsset(id);
          } else {
            await assetApi.deleteCurrentAsset(id);
          }
          message.success('删除成功');
          fetchAssets();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values) => {
    try {
      const data = {
        ...values,
        purchaseDate: values.purchaseDate ? values.purchaseDate.format('YYYY-MM-DD') : null,
      };

      if (editingRecord) {
        if (assetType === 'fixed') {
          await assetApi.updateFixedAsset(editingRecord.id, data);
        } else {
          await assetApi.updateCurrentAsset(editingRecord.id, data);
        }
        message.success('更新成功');
      } else {
        if (assetType === 'fixed') {
          await assetApi.createFixedAsset(data);
        } else {
          await assetApi.createCurrentAsset(data);
        }
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchAssets();
    } catch (error) {
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };

  const fixedAssetColumns = [
    {
      title: '资产名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '资产编号',
      dataIndex: 'assetNo',
      key: 'assetNo',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '购买价格',
      dataIndex: 'purchasePrice',
      key: 'purchasePrice',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '购买日期',
      dataIndex: 'purchaseDate',
      key: 'purchaseDate',
    },
    {
      title: '使用部门',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          active: { color: 'green', text: '使用中' },
          maintenance: { color: 'orange', text: '维修中' },
          idle: { color: 'blue', text: '闲置' },
          scrapped: { color: 'red', text: '已报废' },
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} size="small">
            查看
          </Button>
          <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record, 'fixed')}>
            编辑
          </Button>
          <Button type="link" icon={<SwapOutlined />} size="small">
            调拨
          </Button>
          <Button type="link" icon={<ToolOutlined />} size="small">
            维修
          </Button>
          <Button type="link" icon={<CloseOutlined />} size="small" danger>
            报废
          </Button>
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record.id, 'fixed')}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const currentAssetColumns = [
    {
      title: '资产名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '资产编号',
      dataIndex: 'assetNo',
      key: 'assetNo',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '总价值',
      dataIndex: 'totalValue',
      key: 'totalValue',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '存放位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} size="small">
            查看
          </Button>
          <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record, 'current')}>
            编辑
          </Button>
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record.id, 'current')}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <Tabs defaultActiveKey="fixed">
          <TabPane tab="固定资产" key="fixed">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => handleAdd('fixed')}>
                  新增固定资产
                </Button>
              </Space>
            </div>

            <Table
              columns={fixedAssetColumns}
              dataSource={fixedAssets}
              loading={loading}
              rowKey="id"
              pagination={{
                total: fixedAssets.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </TabPane>

          <TabPane tab="流动资产" key="current">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => handleAdd('current')}>
                  新增流动资产
                </Button>
              </Space>
            </div>

            <Table
              columns={currentAssetColumns}
              dataSource={currentAssets}
              loading={loading}
              rowKey="id"
              pagination={{
                total: currentAssets.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={editingRecord ? '编辑资产' : '新增资产'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="资产名称"
            rules={[{ required: true, message: '请输入资产名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="assetNo"
            label="资产编号"
            rules={[{ required: true, message: '请输入资产编号' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="category"
            label="资产分类"
            rules={[{ required: true, message: '请选择资产分类' }]}
          >
            <Select>
              <Option value="办公设备">办公设备</Option>
              <Option value="电子设备">电子设备</Option>
              <Option value="家具">家具</Option>
              <Option value="车辆">车辆</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>

          {assetType === 'fixed' ? (
            <>
              <Form.Item
                name="purchasePrice"
                label="购买价格"
                rules={[{ required: true, message: '请输入购买价格' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>

              <Form.Item
                name="purchaseDate"
                label="购买日期"
                rules={[{ required: true, message: '请选择购买日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                name="department"
                label="使用部门"
                rules={[{ required: true, message: '请选择使用部门' }]}
              >
                <Select>
                  <Option value="研发部">研发部</Option>
                  <Option value="市场部">市场部</Option>
                  <Option value="人事部">人事部</Option>
                  <Option value="财务部">财务部</Option>
                  <Option value="行政部">行政部</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select>
                  <Option value="active">使用中</Option>
                  <Option value="maintenance">维修中</Option>
                  <Option value="idle">闲置</Option>
                  <Option value="scrapped">已报废</Option>
                </Select>
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                name="quantity"
                label="数量"
                rules={[{ required: true, message: '请输入数量' }]}
              >
                <InputNumber style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                name="unitPrice"
                label="单价"
                rules={[{ required: true, message: '请输入单价' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>

              <Form.Item
                name="location"
                label="存放位置"
                rules={[{ required: true, message: '请输入存放位置' }]}
              >
                <Input />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </div>
  );
}
